Bug 18433: Remember item search results selected rows in session storage
[koha.git] / t / db_dependent / Circulation.t
blob121c1767b418ed9790aa94fd17d2f6a88eb9dcdb
1 #!/usr/bin/perl
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>.
18 use Modern::Perl;
19 use utf8;
21 use Test::More tests => 46;
22 use Test::MockModule;
23 use Test::Deep qw( cmp_deeply );
25 use Data::Dumper;
26 use DateTime;
27 use Time::Fake;
28 use POSIX qw( floor );
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
32 use C4::Accounts;
33 use C4::Calendar;
34 use C4::Circulation;
35 use C4::Biblio;
36 use C4::Items;
37 use C4::Log;
38 use C4::Reserves;
39 use C4::Overdues qw(UpdateFine CalcFine);
40 use Koha::DateUtils;
41 use Koha::Database;
42 use Koha::Items;
43 use Koha::Checkouts;
44 use Koha::Patrons;
45 use Koha::CirculationRules;
46 use Koha::Subscriptions;
47 use Koha::Account::Lines;
48 use Koha::Account::Offsets;
49 use Koha::ActionLogs;
51 sub set_userenv {
52 my ( $library ) = @_;
53 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
56 sub str {
57 my ( $error, $question, $alert ) = @_;
58 my $s;
59 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
60 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
61 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
62 return $s;
65 sub test_debarment_on_checkout {
66 my ($params) = @_;
67 my $item = $params->{item};
68 my $library = $params->{library};
69 my $patron = $params->{patron};
70 my $due_date = $params->{due_date} || dt_from_string;
71 my $return_date = $params->{return_date} || dt_from_string;
72 my $expected_expiration_date = $params->{expiration_date};
74 $expected_expiration_date = output_pref(
76 dt => $expected_expiration_date,
77 dateformat => 'sql',
78 dateonly => 1,
81 my @caller = caller;
82 my $line_number = $caller[2];
83 AddIssue( $patron, $item->{barcode}, $due_date );
85 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
86 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
87 or diag('AddReturn returned message ' . Dumper $message );
88 my $debarments = Koha::Patron::Debarments::GetDebarments(
89 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
90 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
92 is( $debarments->[0]->{expiration},
93 $expected_expiration_date, 'Test at line ' . $line_number );
94 Koha::Patron::Debarments::DelUniqueDebarment(
95 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
98 my $schema = Koha::Database->schema;
99 $schema->storage->txn_begin;
100 my $builder = t::lib::TestBuilder->new;
101 my $dbh = C4::Context->dbh;
103 # Prevent random failures by mocking ->now
104 my $now_value = dt_from_string;
105 my $mocked_datetime = Test::MockModule->new('DateTime');
106 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
108 # Start transaction
109 $dbh->{RaiseError} = 1;
111 my $cache = Koha::Caches->get_instance();
112 $dbh->do(q|DELETE FROM special_holidays|);
113 $dbh->do(q|DELETE FROM repeatable_holidays|);
114 $cache->clear_from_cache('single_holidays');
116 # Start with a clean slate
117 $dbh->do('DELETE FROM issues');
118 $dbh->do('DELETE FROM borrowers');
120 my $library = $builder->build({
121 source => 'Branch',
123 my $library2 = $builder->build({
124 source => 'Branch',
126 my $itemtype = $builder->build(
128 source => 'Itemtype',
129 value => {
130 notforloan => undef,
131 rentalcharge => 0,
132 rentalcharge_daily => 0,
133 defaultreplacecost => undef,
134 processfee => undef
137 )->{itemtype};
138 my $patron_category = $builder->build(
140 source => 'Category',
141 value => {
142 category_type => 'P',
143 enrolmentfee => 0,
144 BlockExpiredPatronOpacActions => -1, # Pick the pref value
149 my $CircControl = C4::Context->preference('CircControl');
150 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
152 my $item = {
153 homebranch => $library2->{branchcode},
154 holdingbranch => $library2->{branchcode}
157 my $borrower = {
158 branchcode => $library2->{branchcode}
161 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
163 # No userenv, PickupLibrary
164 t::lib::Mocks::mock_preference('IndependentBranches', '0');
165 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
167 C4::Context->preference('CircControl'),
168 'PickupLibrary',
169 'CircControl changed to PickupLibrary'
172 C4::Circulation::_GetCircControlBranch($item, $borrower),
173 $item->{$HomeOrHoldingBranch},
174 '_GetCircControlBranch returned item branch (no userenv defined)'
177 # No userenv, PatronLibrary
178 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
180 C4::Context->preference('CircControl'),
181 'PatronLibrary',
182 'CircControl changed to PatronLibrary'
185 C4::Circulation::_GetCircControlBranch($item, $borrower),
186 $borrower->{branchcode},
187 '_GetCircControlBranch returned borrower branch'
190 # No userenv, ItemHomeLibrary
191 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
193 C4::Context->preference('CircControl'),
194 'ItemHomeLibrary',
195 'CircControl changed to ItemHomeLibrary'
198 $item->{$HomeOrHoldingBranch},
199 C4::Circulation::_GetCircControlBranch($item, $borrower),
200 '_GetCircControlBranch returned item branch'
203 # Now, set a userenv
204 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
205 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
207 # Userenv set, PickupLibrary
208 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
210 C4::Context->preference('CircControl'),
211 'PickupLibrary',
212 'CircControl changed to PickupLibrary'
215 C4::Circulation::_GetCircControlBranch($item, $borrower),
216 $library2->{branchcode},
217 '_GetCircControlBranch returned current branch'
220 # Userenv set, PatronLibrary
221 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
223 C4::Context->preference('CircControl'),
224 'PatronLibrary',
225 'CircControl changed to PatronLibrary'
228 C4::Circulation::_GetCircControlBranch($item, $borrower),
229 $borrower->{branchcode},
230 '_GetCircControlBranch returned borrower branch'
233 # Userenv set, ItemHomeLibrary
234 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
236 C4::Context->preference('CircControl'),
237 'ItemHomeLibrary',
238 'CircControl changed to ItemHomeLibrary'
241 C4::Circulation::_GetCircControlBranch($item, $borrower),
242 $item->{$HomeOrHoldingBranch},
243 '_GetCircControlBranch returned item branch'
246 # Reset initial configuration
247 t::lib::Mocks::mock_preference('CircControl', $CircControl);
249 C4::Context->preference('CircControl'),
250 $CircControl,
251 'CircControl reset to its initial value'
254 # Set a simple circ policy
255 $dbh->do('DELETE FROM circulation_rules');
256 Koha::CirculationRules->set_rules(
258 categorycode => undef,
259 branchcode => undef,
260 itemtype => undef,
261 rules => {
262 reservesallowed => 25,
263 issuelength => 14,
264 lengthunit => 'days',
265 renewalsallowed => 1,
266 renewalperiod => 7,
267 norenewalbefore => undef,
268 auto_renew => 0,
269 fine => .10,
270 chargeperiod => 1,
275 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
276 subtest "CanBookBeRenewed tests" => sub {
277 plan tests => 77;
279 C4::Context->set_preference('ItemsDeniedRenewal','');
280 # Generate test biblio
281 my $biblio = $builder->build_sample_biblio();
283 my $branch = $library2->{branchcode};
285 my $item_1 = $builder->build_sample_item(
287 biblionumber => $biblio->biblionumber,
288 library => $branch,
289 replacementprice => 12.00,
290 itype => $itemtype
293 $reused_itemnumber_1 = $item_1->itemnumber;
295 my $item_2 = $builder->build_sample_item(
297 biblionumber => $biblio->biblionumber,
298 library => $branch,
299 replacementprice => 23.00,
300 itype => $itemtype
303 $reused_itemnumber_2 = $item_2->itemnumber;
305 my $item_3 = $builder->build_sample_item(
307 biblionumber => $biblio->biblionumber,
308 library => $branch,
309 replacementprice => 23.00,
310 itype => $itemtype
314 # Create borrowers
315 my %renewing_borrower_data = (
316 firstname => 'John',
317 surname => 'Renewal',
318 categorycode => $patron_category->{categorycode},
319 branchcode => $branch,
322 my %reserving_borrower_data = (
323 firstname => 'Katrin',
324 surname => 'Reservation',
325 categorycode => $patron_category->{categorycode},
326 branchcode => $branch,
329 my %hold_waiting_borrower_data = (
330 firstname => 'Kyle',
331 surname => 'Reservation',
332 categorycode => $patron_category->{categorycode},
333 branchcode => $branch,
336 my %restricted_borrower_data = (
337 firstname => 'Alice',
338 surname => 'Reservation',
339 categorycode => $patron_category->{categorycode},
340 debarred => '3228-01-01',
341 branchcode => $branch,
344 my %expired_borrower_data = (
345 firstname => 'Ça',
346 surname => 'Glisse',
347 categorycode => $patron_category->{categorycode},
348 branchcode => $branch,
349 dateexpiry => dt_from_string->subtract( months => 1 ),
352 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
353 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
354 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
355 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
356 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
358 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
359 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
360 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
362 my $bibitems = '';
363 my $priority = '1';
364 my $resdate = undef;
365 my $expdate = undef;
366 my $notes = '';
367 my $checkitem = undef;
368 my $found = undef;
370 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
371 my $datedue = dt_from_string( $issue->date_due() );
372 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
374 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
375 $datedue = dt_from_string( $issue->date_due() );
376 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
379 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
380 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
382 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
383 is( $renewokay, 1, 'Can renew, no holds for this title or item');
386 # Biblio-level hold, renewal test
387 AddReserve(
389 branchcode => $branch,
390 borrowernumber => $reserving_borrowernumber,
391 biblionumber => $biblio->biblionumber,
392 priority => $priority,
393 reservation_date => $resdate,
394 expiration_date => $expdate,
395 notes => $notes,
396 itemnumber => $checkitem,
397 found => $found,
401 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
402 Koha::CirculationRules->set_rule(
404 categorycode => undef,
405 branchcode => undef,
406 itemtype => undef,
407 rule_name => 'onshelfholds',
408 rule_value => '1',
411 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
412 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
413 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
414 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
415 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
417 # Now let's add an item level hold, we should no longer be able to renew the item
418 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
420 borrowernumber => $hold_waiting_borrowernumber,
421 biblionumber => $biblio->biblionumber,
422 itemnumber => $item_1->itemnumber,
423 branchcode => $branch,
424 priority => 3,
427 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
428 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
429 $hold->delete();
431 # 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
432 # be able to renew these items
433 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
435 borrowernumber => $hold_waiting_borrowernumber,
436 biblionumber => $biblio->biblionumber,
437 itemnumber => $item_3->itemnumber,
438 branchcode => $branch,
439 priority => 0,
440 found => 'W'
443 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
444 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
445 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
446 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
447 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
449 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
450 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
451 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
453 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
454 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
455 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
457 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
458 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
459 AddIssue($reserving_borrower, $item_3->barcode);
460 my $reserve = $dbh->selectrow_hashref(
461 'SELECT * FROM old_reserves WHERE reserve_id = ?',
462 { Slice => {} },
463 $reserveid
465 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
467 # Item-level hold, renewal test
468 AddReserve(
470 branchcode => $branch,
471 borrowernumber => $reserving_borrowernumber,
472 biblionumber => $biblio->biblionumber,
473 priority => $priority,
474 reservation_date => $resdate,
475 expiration_date => $expdate,
476 notes => $notes,
477 itemnumber => $item_1->itemnumber,
478 found => $found,
482 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
483 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
484 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
486 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
487 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
489 # Items can't fill hold for reasons
490 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
491 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
492 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
493 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
495 # FIXME: Add more for itemtype not for loan etc.
497 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
498 my $item_5 = $builder->build_sample_item(
500 biblionumber => $biblio->biblionumber,
501 library => $branch,
502 replacementprice => 23.00,
503 itype => $itemtype,
506 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
507 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
509 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
510 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
511 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
512 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
513 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
515 # Users cannot renew an overdue item
516 my $item_6 = $builder->build_sample_item(
518 biblionumber => $biblio->biblionumber,
519 library => $branch,
520 replacementprice => 23.00,
521 itype => $itemtype,
525 my $item_7 = $builder->build_sample_item(
527 biblionumber => $biblio->biblionumber,
528 library => $branch,
529 replacementprice => 23.00,
530 itype => $itemtype,
534 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
535 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
537 my $now = dt_from_string();
538 my $five_weeks = DateTime::Duration->new(weeks => 5);
539 my $five_weeks_ago = $now - $five_weeks;
540 t::lib::Mocks::mock_preference('finesMode', 'production');
542 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
543 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
545 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
546 C4::Overdues::UpdateFine(
548 issue_id => $passeddatedue1->id(),
549 itemnumber => $item_7->itemnumber,
550 borrowernumber => $renewing_borrower->{borrowernumber},
551 amount => $fine,
552 due => Koha::DateUtils::output_pref($five_weeks_ago)
556 t::lib::Mocks::mock_preference('RenewalLog', 0);
557 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
558 my %params_renewal = (
559 timestamp => { -like => $date . "%" },
560 module => "CIRCULATION",
561 action => "RENEWAL",
563 my %params_issue = (
564 timestamp => { -like => $date . "%" },
565 module => "CIRCULATION",
566 action => "ISSUE"
568 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
569 my $dt = dt_from_string();
570 Time::Fake->offset( $dt->epoch );
571 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
572 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
573 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
574 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
575 Time::Fake->reset;
577 t::lib::Mocks::mock_preference('RenewalLog', 1);
578 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
579 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
580 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
581 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
582 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
584 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
585 is( $fines->count, 2, 'AddRenewal left both fines' );
586 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
587 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
588 $fines->delete();
591 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
592 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
593 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
594 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
595 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
596 $new_log_size = Koha::ActionLogs->count( \%params_issue );
597 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
599 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
600 $fines->delete();
602 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
603 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
604 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
605 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
606 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
609 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
610 $hold->cancel;
612 # Bug 14101
613 # Test automatic renewal before value for "norenewalbefore" in policy is set
614 # In this case automatic renewal is not permitted prior to due date
615 my $item_4 = $builder->build_sample_item(
617 biblionumber => $biblio->biblionumber,
618 library => $branch,
619 replacementprice => 16.00,
620 itype => $itemtype,
624 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
625 ( $renewokay, $error ) =
626 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
627 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
628 is( $error, 'auto_too_soon',
629 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
630 AddReserve(
632 branchcode => $branch,
633 borrowernumber => $reserving_borrowernumber,
634 biblionumber => $biblio->biblionumber,
635 itemnumber => $bibitems,
636 priority => $priority,
637 reservation_date => $resdate,
638 expiration_date => $expdate,
639 notes => $notes,
640 title => 'a title',
641 itemnumber => $item_4->itemnumber,
642 found => $found
645 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
646 is( $renewokay, 0, 'Still should not be able to renew' );
647 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked' );
648 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
649 is( $renewokay, 0, 'Still should not be able to renew' );
650 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
651 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
652 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
653 is( $renewokay, 0, 'Still should not be able to renew' );
654 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
655 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
659 # Bug 7413
660 # Test premature manual renewal
661 Koha::CirculationRules->set_rule(
663 categorycode => undef,
664 branchcode => undef,
665 itemtype => undef,
666 rule_name => 'norenewalbefore',
667 rule_value => '7',
671 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
672 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
673 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
675 # Bug 14395
676 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
677 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
679 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
680 $datedue->clone->add( days => -7 ),
681 'Bug 14395: Renewals permitted 7 days before due date, as expected'
684 # Bug 14395
685 # Test 'date' setting for syspref NoRenewalBeforePrecision
686 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
688 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
689 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
690 'Bug 14395: Renewals permitted 7 days before due date, as expected'
693 # Bug 14101
694 # Test premature automatic renewal
695 ( $renewokay, $error ) =
696 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
697 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
698 is( $error, 'auto_too_soon',
699 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
702 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
703 # and test automatic renewal again
704 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
705 ( $renewokay, $error ) =
706 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
707 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
708 is( $error, 'auto_too_soon',
709 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
712 # Change policy so that loans can be renewed 99 days prior to the due date
713 # and test automatic renewal again
714 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
715 ( $renewokay, $error ) =
716 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
717 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
718 is( $error, 'auto_renew',
719 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
722 subtest "too_late_renewal / no_auto_renewal_after" => sub {
723 plan tests => 14;
724 my $item_to_auto_renew = $builder->build(
725 { source => 'Item',
726 value => {
727 biblionumber => $biblio->biblionumber,
728 homebranch => $branch,
729 holdingbranch => $branch,
734 my $ten_days_before = dt_from_string->add( days => -10 );
735 my $ten_days_ahead = dt_from_string->add( days => 10 );
736 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
738 Koha::CirculationRules->set_rules(
740 categorycode => undef,
741 branchcode => undef,
742 itemtype => undef,
743 rules => {
744 norenewalbefore => '7',
745 no_auto_renewal_after => '9',
749 ( $renewokay, $error ) =
750 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
751 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
752 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
754 Koha::CirculationRules->set_rules(
756 categorycode => undef,
757 branchcode => undef,
758 itemtype => undef,
759 rules => {
760 norenewalbefore => '7',
761 no_auto_renewal_after => '10',
765 ( $renewokay, $error ) =
766 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
767 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
768 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
770 Koha::CirculationRules->set_rules(
772 categorycode => undef,
773 branchcode => undef,
774 itemtype => undef,
775 rules => {
776 norenewalbefore => '7',
777 no_auto_renewal_after => '11',
781 ( $renewokay, $error ) =
782 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
783 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
784 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
786 Koha::CirculationRules->set_rules(
788 categorycode => undef,
789 branchcode => undef,
790 itemtype => undef,
791 rules => {
792 norenewalbefore => '10',
793 no_auto_renewal_after => '11',
797 ( $renewokay, $error ) =
798 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
799 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
800 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
802 Koha::CirculationRules->set_rules(
804 categorycode => undef,
805 branchcode => undef,
806 itemtype => undef,
807 rules => {
808 norenewalbefore => '10',
809 no_auto_renewal_after => undef,
810 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
814 ( $renewokay, $error ) =
815 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
816 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
817 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
819 Koha::CirculationRules->set_rules(
821 categorycode => undef,
822 branchcode => undef,
823 itemtype => undef,
824 rules => {
825 norenewalbefore => '7',
826 no_auto_renewal_after => '15',
827 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
831 ( $renewokay, $error ) =
832 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
833 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
834 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
836 Koha::CirculationRules->set_rules(
838 categorycode => undef,
839 branchcode => undef,
840 itemtype => undef,
841 rules => {
842 norenewalbefore => '10',
843 no_auto_renewal_after => undef,
844 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
848 ( $renewokay, $error ) =
849 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
850 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
851 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
854 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
855 plan tests => 10;
856 my $item_to_auto_renew = $builder->build({
857 source => 'Item',
858 value => {
859 biblionumber => $biblio->biblionumber,
860 homebranch => $branch,
861 holdingbranch => $branch,
865 my $ten_days_before = dt_from_string->add( days => -10 );
866 my $ten_days_ahead = dt_from_string->add( days => 10 );
867 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
869 Koha::CirculationRules->set_rules(
871 categorycode => undef,
872 branchcode => undef,
873 itemtype => undef,
874 rules => {
875 norenewalbefore => '10',
876 no_auto_renewal_after => '11',
880 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
881 C4::Context->set_preference('OPACFineNoRenewals','10');
882 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
883 my $fines_amount = 5;
884 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
885 $account->add_debit(
887 amount => $fines_amount,
888 interface => 'test',
889 type => 'OVERDUE',
890 item_id => $item_to_auto_renew->{itemnumber},
891 description => "Some fines"
893 )->status('RETURNED')->store;
894 ( $renewokay, $error ) =
895 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
896 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
897 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
899 $account->add_debit(
901 amount => $fines_amount,
902 interface => 'test',
903 type => 'OVERDUE',
904 item_id => $item_to_auto_renew->{itemnumber},
905 description => "Some fines"
907 )->status('RETURNED')->store;
908 ( $renewokay, $error ) =
909 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
910 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
911 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
913 $account->add_debit(
915 amount => $fines_amount,
916 interface => 'test',
917 type => 'OVERDUE',
918 item_id => $item_to_auto_renew->{itemnumber},
919 description => "Some fines"
921 )->status('RETURNED')->store;
922 ( $renewokay, $error ) =
923 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
924 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
925 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
927 $account->add_credit(
929 amount => $fines_amount,
930 interface => 'test',
931 type => 'PAYMENT',
932 description => "Some payment"
934 )->store;
935 ( $renewokay, $error ) =
936 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
937 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
938 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
940 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
941 ( $renewokay, $error ) =
942 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
943 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
944 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
946 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
947 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
950 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
951 plan tests => 6;
952 my $item_to_auto_renew = $builder->build({
953 source => 'Item',
954 value => {
955 biblionumber => $biblio->biblionumber,
956 homebranch => $branch,
957 holdingbranch => $branch,
961 Koha::CirculationRules->set_rules(
963 categorycode => undef,
964 branchcode => undef,
965 itemtype => undef,
966 rules => {
967 norenewalbefore => 10,
968 no_auto_renewal_after => 11,
973 my $ten_days_before = dt_from_string->add( days => -10 );
974 my $ten_days_ahead = dt_from_string->add( days => 10 );
976 # Patron is expired and BlockExpiredPatronOpacActions=0
977 # => auto renew is allowed
978 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
979 my $patron = $expired_borrower;
980 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
981 ( $renewokay, $error ) =
982 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
983 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
984 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
985 Koha::Checkouts->find( $checkout->issue_id )->delete;
988 # Patron is expired and BlockExpiredPatronOpacActions=1
989 # => auto renew is not allowed
990 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
991 $patron = $expired_borrower;
992 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
993 ( $renewokay, $error ) =
994 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
995 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
996 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
997 Koha::Checkouts->find( $checkout->issue_id )->delete;
1000 # Patron is not expired and BlockExpiredPatronOpacActions=1
1001 # => auto renew is allowed
1002 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1003 $patron = $renewing_borrower;
1004 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1005 ( $renewokay, $error ) =
1006 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1007 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1008 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1009 Koha::Checkouts->find( $checkout->issue_id )->delete;
1012 subtest "GetLatestAutoRenewDate" => sub {
1013 plan tests => 5;
1014 my $item_to_auto_renew = $builder->build(
1015 { source => 'Item',
1016 value => {
1017 biblionumber => $biblio->biblionumber,
1018 homebranch => $branch,
1019 holdingbranch => $branch,
1024 my $ten_days_before = dt_from_string->add( days => -10 );
1025 my $ten_days_ahead = dt_from_string->add( days => 10 );
1026 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1027 Koha::CirculationRules->set_rules(
1029 categorycode => undef,
1030 branchcode => undef,
1031 itemtype => undef,
1032 rules => {
1033 norenewalbefore => '7',
1034 no_auto_renewal_after => '',
1035 no_auto_renewal_after_hard_limit => undef,
1039 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1040 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' );
1041 my $five_days_before = dt_from_string->add( days => -5 );
1042 Koha::CirculationRules->set_rules(
1044 categorycode => undef,
1045 branchcode => undef,
1046 itemtype => undef,
1047 rules => {
1048 norenewalbefore => '10',
1049 no_auto_renewal_after => '5',
1050 no_auto_renewal_after_hard_limit => undef,
1054 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1055 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1056 $five_days_before->truncate( to => 'minute' ),
1057 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1059 my $five_days_ahead = dt_from_string->add( days => 5 );
1060 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1061 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1062 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1063 Koha::CirculationRules->set_rules(
1065 categorycode => undef,
1066 branchcode => undef,
1067 itemtype => undef,
1068 rules => {
1069 norenewalbefore => '10',
1070 no_auto_renewal_after => '15',
1071 no_auto_renewal_after_hard_limit => undef,
1075 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1076 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1077 $five_days_ahead->truncate( to => 'minute' ),
1078 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1080 my $two_days_ahead = dt_from_string->add( days => 2 );
1081 Koha::CirculationRules->set_rules(
1083 categorycode => undef,
1084 branchcode => undef,
1085 itemtype => undef,
1086 rules => {
1087 norenewalbefore => '10',
1088 no_auto_renewal_after => '',
1089 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1093 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1094 is( $latest_auto_renew_date->truncate( to => 'day' ),
1095 $two_days_ahead->truncate( to => 'day' ),
1096 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1098 Koha::CirculationRules->set_rules(
1100 categorycode => undef,
1101 branchcode => undef,
1102 itemtype => undef,
1103 rules => {
1104 norenewalbefore => '10',
1105 no_auto_renewal_after => '15',
1106 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1110 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1111 is( $latest_auto_renew_date->truncate( to => 'day' ),
1112 $two_days_ahead->truncate( to => 'day' ),
1113 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1117 # Too many renewals
1119 # set policy to forbid renewals
1120 Koha::CirculationRules->set_rules(
1122 categorycode => undef,
1123 branchcode => undef,
1124 itemtype => undef,
1125 rules => {
1126 norenewalbefore => undef,
1127 renewalsallowed => 0,
1132 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1133 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1134 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1136 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1137 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1138 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1140 C4::Overdues::UpdateFine(
1142 issue_id => $issue->id(),
1143 itemnumber => $item_1->itemnumber,
1144 borrowernumber => $renewing_borrower->{borrowernumber},
1145 amount => 15.00,
1146 type => q{},
1147 due => Koha::DateUtils::output_pref($datedue)
1151 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1152 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1153 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1154 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1155 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1156 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1158 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1159 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1160 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1162 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1163 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1165 LostItem( $item_1->itemnumber, 'test', 1 );
1167 $line = Koha::Account::Lines->find($line->id);
1168 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1169 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1171 my $item = Koha::Items->find($item_1->itemnumber);
1172 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1173 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1174 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1176 my $total_due = $dbh->selectrow_array(
1177 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1178 undef, $renewing_borrower->{borrowernumber}
1181 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1183 C4::Context->dbh->do("DELETE FROM accountlines");
1185 C4::Overdues::UpdateFine(
1187 issue_id => $issue2->id(),
1188 itemnumber => $item_2->itemnumber,
1189 borrowernumber => $renewing_borrower->{borrowernumber},
1190 amount => 15.00,
1191 type => q{},
1192 due => Koha::DateUtils::output_pref($datedue)
1196 LostItem( $item_2->itemnumber, 'test', 0 );
1198 my $item2 = Koha::Items->find($item_2->itemnumber);
1199 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1200 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1202 $total_due = $dbh->selectrow_array(
1203 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1204 undef, $renewing_borrower->{borrowernumber}
1207 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1209 my $future = dt_from_string();
1210 $future->add( days => 7 );
1211 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1212 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1214 # Users cannot renew any item if there is an overdue item
1215 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1216 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1217 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1218 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1219 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1221 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1222 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1223 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1224 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1225 LostItem( $item_3->itemnumber, 'test', 0 );
1226 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1227 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1229 $accountline->description,
1230 sprintf( "%s %s %s",
1231 $item_3->biblio->title || '',
1232 $item_3->barcode || '',
1233 $item_3->itemcallnumber || '' ),
1234 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1238 subtest "GetUpcomingDueIssues" => sub {
1239 plan tests => 12;
1241 my $branch = $library2->{branchcode};
1243 #Create another record
1244 my $biblio2 = $builder->build_sample_biblio();
1246 #Create third item
1247 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1248 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1249 my $item_3 = $builder->build_sample_item(
1251 biblionumber => $biblio2->biblionumber,
1252 library => $branch,
1253 itype => $itemtype,
1258 # Create a borrower
1259 my %a_borrower_data = (
1260 firstname => 'Fridolyn',
1261 surname => 'SOMERS',
1262 categorycode => $patron_category->{categorycode},
1263 branchcode => $branch,
1266 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1267 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1269 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1270 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1271 my $today = DateTime->today(time_zone => C4::Context->tz());
1273 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1274 my $datedue = dt_from_string( $issue->date_due() );
1275 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1276 my $datedue2 = dt_from_string( $issue->date_due() );
1278 my $upcoming_dues;
1280 # GetUpcomingDueIssues tests
1281 for my $i(0..1) {
1282 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1283 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1286 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1287 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1288 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1290 for my $i(3..5) {
1291 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1292 is ( scalar( @$upcoming_dues ), 1,
1293 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1296 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1298 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1300 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1301 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1303 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1304 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1306 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1307 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1309 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1310 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1312 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1313 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1315 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1316 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1320 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1321 my $branch = $library2->{branchcode};
1323 my $biblio = $builder->build_sample_biblio();
1325 #Create third item
1326 my $item = $builder->build_sample_item(
1328 biblionumber => $biblio->biblionumber,
1329 library => $branch,
1330 itype => $itemtype,
1334 # Create a borrower
1335 my %a_borrower_data = (
1336 firstname => 'Kyle',
1337 surname => 'Hall',
1338 categorycode => $patron_category->{categorycode},
1339 branchcode => $branch,
1342 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1344 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1345 my $issue = AddIssue( $borrower, $item->barcode );
1346 UpdateFine(
1348 issue_id => $issue->id(),
1349 itemnumber => $item->itemnumber,
1350 borrowernumber => $borrowernumber,
1351 amount => 0,
1352 type => q{}
1356 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1357 my $count = $hr->{count};
1359 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1362 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1363 $dbh->do('DELETE FROM issues');
1364 $dbh->do('DELETE FROM items');
1365 $dbh->do('DELETE FROM circulation_rules');
1366 Koha::CirculationRules->set_rules(
1368 categorycode => undef,
1369 itemtype => undef,
1370 branchcode => undef,
1371 rules => {
1372 reservesallowed => 25,
1373 issuelength => 14,
1374 lengthunit => 'days',
1375 renewalsallowed => 1,
1376 renewalperiod => 7,
1377 norenewalbefore => undef,
1378 auto_renew => 0,
1379 fine => .10,
1380 chargeperiod => 1,
1381 maxissueqty => 20
1385 my $biblio = $builder->build_sample_biblio();
1387 my $item_1 = $builder->build_sample_item(
1389 biblionumber => $biblio->biblionumber,
1390 library => $library2->{branchcode},
1391 itype => $itemtype,
1395 my $item_2= $builder->build_sample_item(
1397 biblionumber => $biblio->biblionumber,
1398 library => $library2->{branchcode},
1399 itype => $itemtype,
1403 my $borrowernumber1 = Koha::Patron->new({
1404 firstname => 'Kyle',
1405 surname => 'Hall',
1406 categorycode => $patron_category->{categorycode},
1407 branchcode => $library2->{branchcode},
1408 })->store->borrowernumber;
1409 my $borrowernumber2 = Koha::Patron->new({
1410 firstname => 'Chelsea',
1411 surname => 'Hall',
1412 categorycode => $patron_category->{categorycode},
1413 branchcode => $library2->{branchcode},
1414 })->store->borrowernumber;
1416 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1417 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1419 my $issue = AddIssue( $borrower1, $item_1->barcode );
1421 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1422 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1424 AddReserve(
1426 branchcode => $library2->{branchcode},
1427 borrowernumber => $borrowernumber2,
1428 biblionumber => $biblio->biblionumber,
1429 priority => 1,
1433 Koha::CirculationRules->set_rules(
1435 categorycode => undef,
1436 itemtype => undef,
1437 branchcode => undef,
1438 rules => {
1439 onshelfholds => 0,
1443 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1444 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1445 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1447 Koha::CirculationRules->set_rules(
1449 categorycode => undef,
1450 itemtype => undef,
1451 branchcode => undef,
1452 rules => {
1453 onshelfholds => 0,
1457 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1458 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1459 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1461 Koha::CirculationRules->set_rules(
1463 categorycode => undef,
1464 itemtype => undef,
1465 branchcode => undef,
1466 rules => {
1467 onshelfholds => 1,
1471 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1472 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1473 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1475 Koha::CirculationRules->set_rules(
1477 categorycode => undef,
1478 itemtype => undef,
1479 branchcode => undef,
1480 rules => {
1481 onshelfholds => 1,
1485 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1486 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1487 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1489 # Setting item not checked out to be not for loan but holdable
1490 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1492 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1493 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' );
1497 # Don't allow renewing onsite checkout
1498 my $branch = $library->{branchcode};
1500 #Create another record
1501 my $biblio = $builder->build_sample_biblio();
1503 my $item = $builder->build_sample_item(
1505 biblionumber => $biblio->biblionumber,
1506 library => $branch,
1507 itype => $itemtype,
1511 my $borrowernumber = Koha::Patron->new({
1512 firstname => 'fn',
1513 surname => 'dn',
1514 categorycode => $patron_category->{categorycode},
1515 branchcode => $branch,
1516 })->store->borrowernumber;
1518 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1520 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1521 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1522 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1523 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1527 my $library = $builder->build({ source => 'Branch' });
1529 my $biblio = $builder->build_sample_biblio();
1531 my $item = $builder->build_sample_item(
1533 biblionumber => $biblio->biblionumber,
1534 library => $library->{branchcode},
1535 itype => $itemtype,
1539 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1541 my $issue = AddIssue( $patron, $item->barcode );
1542 UpdateFine(
1544 issue_id => $issue->id(),
1545 itemnumber => $item->itemnumber,
1546 borrowernumber => $patron->{borrowernumber},
1547 amount => 1,
1548 type => q{}
1551 UpdateFine(
1553 issue_id => $issue->id(),
1554 itemnumber => $item->itemnumber,
1555 borrowernumber => $patron->{borrowernumber},
1556 amount => 2,
1557 type => q{}
1560 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1563 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1564 plan tests => 24;
1566 my $homebranch = $builder->build( { source => 'Branch' } );
1567 my $holdingbranch = $builder->build( { source => 'Branch' } );
1568 my $otherbranch = $builder->build( { source => 'Branch' } );
1569 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1570 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1572 my $item = $builder->build_sample_item(
1574 homebranch => $homebranch->{branchcode},
1575 holdingbranch => $holdingbranch->{branchcode},
1577 )->unblessed;
1579 set_userenv($holdingbranch);
1581 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1582 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1584 my ( $error, $question, $alerts );
1586 # AllowReturnToBranch == anywhere
1587 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1588 ## Test that unknown barcodes don't generate internal server errors
1589 set_userenv($homebranch);
1590 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1591 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1592 ## Can be issued from homebranch
1593 set_userenv($homebranch);
1594 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1595 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1596 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1597 ## Can be issued from holdingbranch
1598 set_userenv($holdingbranch);
1599 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1600 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1601 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1602 ## Can be issued from another branch
1603 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1604 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1605 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1607 # AllowReturnToBranch == holdingbranch
1608 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1609 ## Cannot be issued from homebranch
1610 set_userenv($homebranch);
1611 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1612 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1613 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1614 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1615 ## Can be issued from holdinbranch
1616 set_userenv($holdingbranch);
1617 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1618 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1619 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1620 ## Cannot be issued from another branch
1621 set_userenv($otherbranch);
1622 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1623 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1624 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1625 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1627 # AllowReturnToBranch == homebranch
1628 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1629 ## Can be issued from holdinbranch
1630 set_userenv($homebranch);
1631 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1632 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1633 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1634 ## Cannot be issued from holdinbranch
1635 set_userenv($holdingbranch);
1636 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1637 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1638 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1639 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1640 ## Cannot be issued from holdinbranch
1641 set_userenv($otherbranch);
1642 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1643 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1644 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1645 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1647 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1650 subtest 'AddIssue & AllowReturnToBranch' => sub {
1651 plan tests => 9;
1653 my $homebranch = $builder->build( { source => 'Branch' } );
1654 my $holdingbranch = $builder->build( { source => 'Branch' } );
1655 my $otherbranch = $builder->build( { source => 'Branch' } );
1656 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1657 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1659 my $item = $builder->build_sample_item(
1661 homebranch => $homebranch->{branchcode},
1662 holdingbranch => $holdingbranch->{branchcode},
1664 )->unblessed;
1666 set_userenv($holdingbranch);
1668 my $ref_issue = 'Koha::Checkout';
1669 my $issue = AddIssue( $patron_1, $item->{barcode} );
1671 my ( $error, $question, $alerts );
1673 # AllowReturnToBranch == homebranch
1674 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1675 ## Can be issued from homebranch
1676 set_userenv($homebranch);
1677 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1678 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1679 ## Can be issued from holdinbranch
1680 set_userenv($holdingbranch);
1681 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1682 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1683 ## Can be issued from another branch
1684 set_userenv($otherbranch);
1685 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1686 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1688 # AllowReturnToBranch == holdinbranch
1689 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1690 ## Cannot be issued from homebranch
1691 set_userenv($homebranch);
1692 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1693 ## Can be issued from holdingbranch
1694 set_userenv($holdingbranch);
1695 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1696 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1697 ## Cannot be issued from another branch
1698 set_userenv($otherbranch);
1699 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1701 # AllowReturnToBranch == homebranch
1702 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1703 ## Can be issued from homebranch
1704 set_userenv($homebranch);
1705 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1706 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1707 ## Cannot be issued from holdinbranch
1708 set_userenv($holdingbranch);
1709 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1710 ## Cannot be issued from another branch
1711 set_userenv($otherbranch);
1712 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1713 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1716 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1717 plan tests => 8;
1719 my $library = $builder->build( { source => 'Branch' } );
1720 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1721 my $item_1 = $builder->build_sample_item(
1723 library => $library->{branchcode},
1725 )->unblessed;
1726 my $item_2 = $builder->build_sample_item(
1728 library => $library->{branchcode},
1730 )->unblessed;
1732 my ( $error, $question, $alerts );
1734 # Patron cannot issue item_1, they have overdues
1735 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1736 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1738 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1739 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1740 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1741 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1743 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1744 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1745 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1746 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1748 # Patron cannot issue item_1, they are debarred
1749 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1750 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1751 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1752 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1753 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1755 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1756 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1757 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1758 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1761 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1762 plan tests => 1;
1764 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1765 my $patron_category_x = $builder->build_object(
1767 class => 'Koha::Patron::Categories',
1768 value => { category_type => 'X' }
1771 my $patron = $builder->build_object(
1773 class => 'Koha::Patrons',
1774 value => {
1775 categorycode => $patron_category_x->categorycode,
1776 gonenoaddress => undef,
1777 lost => undef,
1778 debarred => undef,
1779 borrowernotes => ""
1783 my $item_1 = $builder->build_sample_item(
1785 library => $library->{branchcode},
1787 )->unblessed;
1789 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1790 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1792 # TODO There are other tests to provide here
1795 subtest 'MultipleReserves' => sub {
1796 plan tests => 3;
1798 my $biblio = $builder->build_sample_biblio();
1800 my $branch = $library2->{branchcode};
1802 my $item_1 = $builder->build_sample_item(
1804 biblionumber => $biblio->biblionumber,
1805 library => $branch,
1806 replacementprice => 12.00,
1807 itype => $itemtype,
1811 my $item_2 = $builder->build_sample_item(
1813 biblionumber => $biblio->biblionumber,
1814 library => $branch,
1815 replacementprice => 12.00,
1816 itype => $itemtype,
1820 my $bibitems = '';
1821 my $priority = '1';
1822 my $resdate = undef;
1823 my $expdate = undef;
1824 my $notes = '';
1825 my $checkitem = undef;
1826 my $found = undef;
1828 my %renewing_borrower_data = (
1829 firstname => 'John',
1830 surname => 'Renewal',
1831 categorycode => $patron_category->{categorycode},
1832 branchcode => $branch,
1834 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1835 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1836 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1837 my $datedue = dt_from_string( $issue->date_due() );
1838 is (defined $issue->date_due(), 1, "item 1 checked out");
1839 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1841 my %reserving_borrower_data1 = (
1842 firstname => 'Katrin',
1843 surname => 'Reservation',
1844 categorycode => $patron_category->{categorycode},
1845 branchcode => $branch,
1847 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1848 AddReserve(
1850 branchcode => $branch,
1851 borrowernumber => $reserving_borrowernumber1,
1852 biblionumber => $biblio->biblionumber,
1853 priority => $priority,
1854 reservation_date => $resdate,
1855 expiration_date => $expdate,
1856 notes => $notes,
1857 itemnumber => $checkitem,
1858 found => $found,
1862 my %reserving_borrower_data2 = (
1863 firstname => 'Kirk',
1864 surname => 'Reservation',
1865 categorycode => $patron_category->{categorycode},
1866 branchcode => $branch,
1868 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1869 AddReserve(
1871 branchcode => $branch,
1872 borrowernumber => $reserving_borrowernumber2,
1873 biblionumber => $biblio->biblionumber,
1874 priority => $priority,
1875 reservation_date => $resdate,
1876 expiration_date => $expdate,
1877 notes => $notes,
1878 itemnumber => $checkitem,
1879 found => $found,
1884 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1885 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1888 my $item_3 = $builder->build_sample_item(
1890 biblionumber => $biblio->biblionumber,
1891 library => $branch,
1892 replacementprice => 12.00,
1893 itype => $itemtype,
1898 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1899 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1903 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1904 plan tests => 5;
1906 my $library = $builder->build( { source => 'Branch' } );
1907 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1909 my $biblionumber = $builder->build_sample_biblio(
1911 branchcode => $library->{branchcode},
1913 )->biblionumber;
1914 my $item_1 = $builder->build_sample_item(
1916 biblionumber => $biblionumber,
1917 library => $library->{branchcode},
1919 )->unblessed;
1921 my $item_2 = $builder->build_sample_item(
1923 biblionumber => $biblionumber,
1924 library => $library->{branchcode},
1926 )->unblessed;
1928 my ( $error, $question, $alerts );
1929 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1931 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1932 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1933 cmp_deeply(
1934 { error => $error, alerts => $alerts },
1935 { error => {}, alerts => {} },
1936 'No error or alert should be raised'
1938 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
1940 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1941 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1942 cmp_deeply(
1943 { error => $error, question => $question, alerts => $alerts },
1944 { error => {}, question => {}, alerts => {} },
1945 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
1948 # Add a subscription
1949 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1951 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1952 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1953 cmp_deeply(
1954 { error => $error, question => $question, alerts => $alerts },
1955 { error => {}, question => {}, alerts => {} },
1956 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1959 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1960 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1961 cmp_deeply(
1962 { error => $error, question => $question, alerts => $alerts },
1963 { error => {}, question => {}, alerts => {} },
1964 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1968 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1969 plan tests => 8;
1971 my $library = $builder->build( { source => 'Branch' } );
1972 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1974 # Add 2 items
1975 my $biblionumber = $builder->build_sample_biblio(
1977 branchcode => $library->{branchcode},
1979 )->biblionumber;
1980 my $item_1 = $builder->build_sample_item(
1982 biblionumber => $biblionumber,
1983 library => $library->{branchcode},
1985 )->unblessed;
1986 my $item_2 = $builder->build_sample_item(
1988 biblionumber => $biblionumber,
1989 library => $library->{branchcode},
1991 )->unblessed;
1993 # And the circulation rule
1994 Koha::CirculationRules->search->delete;
1995 Koha::CirculationRules->set_rules(
1997 categorycode => undef,
1998 itemtype => undef,
1999 branchcode => undef,
2000 rules => {
2001 issuelength => 1,
2002 firstremind => 1, # 1 day of grace
2003 finedays => 2, # 2 days of fine per day of overdue
2004 lengthunit => 'days',
2009 # Patron cannot issue item_1, they have overdues
2010 my $five_days_ago = dt_from_string->subtract( days => 5 );
2011 my $ten_days_ago = dt_from_string->subtract( days => 10 );
2012 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
2013 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2014 ; # Add another overdue
2016 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2017 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
2018 my $debarments = Koha::Patron::Debarments::GetDebarments(
2019 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2020 is( scalar(@$debarments), 1 );
2022 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2023 # Same for the others
2024 my $expected_expiration = output_pref(
2026 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
2027 dateformat => 'sql',
2028 dateonly => 1
2031 is( $debarments->[0]->{expiration}, $expected_expiration );
2033 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
2034 $debarments = Koha::Patron::Debarments::GetDebarments(
2035 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2036 is( scalar(@$debarments), 1 );
2037 $expected_expiration = output_pref(
2039 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
2040 dateformat => 'sql',
2041 dateonly => 1
2044 is( $debarments->[0]->{expiration}, $expected_expiration );
2046 Koha::Patron::Debarments::DelUniqueDebarment(
2047 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2049 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2050 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
2051 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2052 ; # Add another overdue
2053 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
2054 $debarments = Koha::Patron::Debarments::GetDebarments(
2055 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2056 is( scalar(@$debarments), 1 );
2057 $expected_expiration = output_pref(
2059 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
2060 dateformat => 'sql',
2061 dateonly => 1
2064 is( $debarments->[0]->{expiration}, $expected_expiration );
2066 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
2067 $debarments = Koha::Patron::Debarments::GetDebarments(
2068 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2069 is( scalar(@$debarments), 1 );
2070 $expected_expiration = output_pref(
2072 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2073 dateformat => 'sql',
2074 dateonly => 1
2077 is( $debarments->[0]->{expiration}, $expected_expiration );
2080 subtest 'AddReturn + suspension_chargeperiod' => sub {
2081 plan tests => 21;
2083 my $library = $builder->build( { source => 'Branch' } );
2084 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2086 my $biblionumber = $builder->build_sample_biblio(
2088 branchcode => $library->{branchcode},
2090 )->biblionumber;
2091 my $item_1 = $builder->build_sample_item(
2093 biblionumber => $biblionumber,
2094 library => $library->{branchcode},
2096 )->unblessed;
2098 # And the issuing rule
2099 Koha::CirculationRules->search->delete;
2100 Koha::CirculationRules->set_rules(
2102 categorycode => '*',
2103 itemtype => '*',
2104 branchcode => '*',
2105 rules => {
2106 issuelength => 1,
2107 firstremind => 0, # 0 day of grace
2108 finedays => 2, # 2 days of fine per day of overdue
2109 suspension_chargeperiod => 1,
2110 lengthunit => 'days',
2115 my $five_days_ago = dt_from_string->subtract( days => 5 );
2116 # We want to charge 2 days every day, without grace
2117 # With 5 days of overdue: 5 * Z
2118 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
2119 test_debarment_on_checkout(
2121 item => $item_1,
2122 library => $library,
2123 patron => $patron,
2124 due_date => $five_days_ago,
2125 expiration_date => $expected_expiration,
2129 # We want to charge 2 days every 2 days, without grace
2130 # With 5 days of overdue: (5 * 2) / 2
2131 Koha::CirculationRules->set_rule(
2133 categorycode => undef,
2134 branchcode => undef,
2135 itemtype => undef,
2136 rule_name => 'suspension_chargeperiod',
2137 rule_value => '2',
2141 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
2142 test_debarment_on_checkout(
2144 item => $item_1,
2145 library => $library,
2146 patron => $patron,
2147 due_date => $five_days_ago,
2148 expiration_date => $expected_expiration,
2152 # We want to charge 2 days every 3 days, with 1 day of grace
2153 # With 5 days of overdue: ((5-1) / 3 ) * 2
2154 Koha::CirculationRules->set_rules(
2156 categorycode => undef,
2157 branchcode => undef,
2158 itemtype => undef,
2159 rules => {
2160 suspension_chargeperiod => 3,
2161 firstremind => 1,
2165 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2166 test_debarment_on_checkout(
2168 item => $item_1,
2169 library => $library,
2170 patron => $patron,
2171 due_date => $five_days_ago,
2172 expiration_date => $expected_expiration,
2176 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2177 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2178 Koha::CirculationRules->set_rules(
2180 categorycode => undef,
2181 branchcode => undef,
2182 itemtype => undef,
2183 rules => {
2184 finedays => 2,
2185 suspension_chargeperiod => 1,
2186 firstremind => 0,
2190 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2191 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2193 # Adding a holiday 2 days ago
2194 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2195 my $two_days_ago = dt_from_string->subtract( days => 2 );
2196 $calendar->insert_single_holiday(
2197 day => $two_days_ago->day,
2198 month => $two_days_ago->month,
2199 year => $two_days_ago->year,
2200 title => 'holidayTest-2d',
2201 description => 'holidayDesc 2 days ago'
2203 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2204 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2205 test_debarment_on_checkout(
2207 item => $item_1,
2208 library => $library,
2209 patron => $patron,
2210 due_date => $five_days_ago,
2211 expiration_date => $expected_expiration,
2215 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2216 my $two_days_ahead = dt_from_string->add( days => 2 );
2217 $calendar->insert_single_holiday(
2218 day => $two_days_ahead->day,
2219 month => $two_days_ahead->month,
2220 year => $two_days_ahead->year,
2221 title => 'holidayTest+2d',
2222 description => 'holidayDesc 2 days ahead'
2225 # Same as above, but we should skip D+2
2226 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2227 test_debarment_on_checkout(
2229 item => $item_1,
2230 library => $library,
2231 patron => $patron,
2232 due_date => $five_days_ago,
2233 expiration_date => $expected_expiration,
2237 # Adding another holiday, day of expiration date
2238 my $expected_expiration_dt = dt_from_string($expected_expiration);
2239 $calendar->insert_single_holiday(
2240 day => $expected_expiration_dt->day,
2241 month => $expected_expiration_dt->month,
2242 year => $expected_expiration_dt->year,
2243 title => 'holidayTest_exp',
2244 description => 'holidayDesc on expiration date'
2246 # Expiration date will be the day after
2247 test_debarment_on_checkout(
2249 item => $item_1,
2250 library => $library,
2251 patron => $patron,
2252 due_date => $five_days_ago,
2253 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2257 test_debarment_on_checkout(
2259 item => $item_1,
2260 library => $library,
2261 patron => $patron,
2262 return_date => dt_from_string->add(days => 5),
2263 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
2268 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2269 plan tests => 2;
2271 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2272 my $patron1 = $builder->build_object(
2274 class => 'Koha::Patrons',
2275 value => {
2276 library => $library->branchcode,
2277 categorycode => $patron_category->{categorycode}
2281 my $patron2 = $builder->build_object(
2283 class => 'Koha::Patrons',
2284 value => {
2285 library => $library->branchcode,
2286 categorycode => $patron_category->{categorycode}
2291 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2293 my $item = $builder->build_sample_item(
2295 library => $library->branchcode,
2297 )->unblessed;
2299 my ( $error, $question, $alerts );
2300 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2302 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2303 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2304 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' );
2306 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2307 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2308 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' );
2310 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2314 subtest 'AddReturn | is_overdue' => sub {
2315 plan tests => 5;
2317 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2318 t::lib::Mocks::mock_preference('finesMode', 'production');
2319 t::lib::Mocks::mock_preference('MaxFine', '100');
2321 my $library = $builder->build( { source => 'Branch' } );
2322 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2323 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2324 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2326 my $item = $builder->build_sample_item(
2328 library => $library->{branchcode},
2329 replacementprice => 7
2331 )->unblessed;
2333 Koha::CirculationRules->search->delete;
2334 Koha::CirculationRules->set_rules(
2336 categorycode => undef,
2337 itemtype => undef,
2338 branchcode => undef,
2339 rules => {
2340 issuelength => 6,
2341 lengthunit => 'days',
2342 fine => 1, # Charge 1 every day of overdue
2343 chargeperiod => 1,
2348 my $now = dt_from_string;
2349 my $one_day_ago = dt_from_string->subtract( days => 1 );
2350 my $five_days_ago = dt_from_string->subtract( days => 5 );
2351 my $ten_days_ago = dt_from_string->subtract( days => 10 );
2352 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2354 # No return date specified, today will be used => 10 days overdue charged
2355 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2356 AddReturn( $item->{barcode}, $library->{branchcode} );
2357 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2358 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2360 # specify return date 5 days before => no overdue charged
2361 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2362 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2363 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2364 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2366 # specify return date 5 days later => 5 days overdue charged
2367 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2368 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2369 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2370 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2372 # specify return date 5 days later, specify exemptfine => no overdue charge
2373 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2374 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2375 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2376 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2378 subtest 'bug 22877' => sub {
2380 plan tests => 3;
2382 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2384 # Fake fines cronjob on this checkout
2385 my ($fine) =
2386 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2387 $ten_days_ago, $now );
2388 UpdateFine(
2390 issue_id => $issue->issue_id,
2391 itemnumber => $item->{itemnumber},
2392 borrowernumber => $patron->borrowernumber,
2393 amount => $fine,
2394 due => output_pref($ten_days_ago)
2397 is( int( $patron->account->balance() ),
2398 10, "Overdue fine of 10 days overdue" );
2400 # Fake longoverdue with charge and not marking returned
2401 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2402 is( int( $patron->account->balance() ),
2403 17, "Lost fine of 7 plus 10 days overdue" );
2405 # Now we return it today
2406 AddReturn( $item->{barcode}, $library->{branchcode} );
2407 is( int( $patron->account->balance() ),
2408 17, "Should have a single 10 days overdue fine and lost charge" );
2412 subtest '_FixAccountForLostAndFound' => sub {
2414 plan tests => 5;
2416 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2417 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2419 my $processfee_amount = 20;
2420 my $replacement_amount = 99.00;
2421 my $item_type = $builder->build_object(
2422 { class => 'Koha::ItemTypes',
2423 value => {
2424 notforloan => undef,
2425 rentalcharge => 0,
2426 defaultreplacecost => undef,
2427 processfee => $processfee_amount,
2428 rentalcharge_daily => 0,
2432 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2434 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2436 subtest 'Full write-off tests' => sub {
2438 plan tests => 12;
2440 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2441 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2442 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2444 my $item = $builder->build_sample_item(
2446 biblionumber => $biblio->biblionumber,
2447 library => $library->branchcode,
2448 replacementprice => $replacement_amount,
2449 itype => $item_type->itemtype,
2453 AddIssue( $patron->unblessed, $item->barcode );
2455 # Simulate item marked as lost
2456 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2457 LostItem( $item->itemnumber, 1 );
2459 my $processing_fee_lines = Koha::Account::Lines->search(
2460 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2461 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2462 my $processing_fee_line = $processing_fee_lines->next;
2463 is( $processing_fee_line->amount + 0,
2464 $processfee_amount, 'The right PROCESSING amount is generated' );
2465 is( $processing_fee_line->amountoutstanding + 0,
2466 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2468 my $lost_fee_lines = Koha::Account::Lines->search(
2469 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2470 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2471 my $lost_fee_line = $lost_fee_lines->next;
2472 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2473 is( $lost_fee_line->amountoutstanding + 0,
2474 $replacement_amount, 'The right LOST amountoutstanding is generated' );
2475 is( $lost_fee_line->status,
2476 undef, 'The LOST status was not set' );
2478 my $account = $patron->account;
2479 my $debts = $account->outstanding_debits;
2481 # Write off the debt
2482 my $credit = $account->add_credit(
2483 { amount => $account->balance,
2484 type => 'WRITEOFF',
2485 interface => 'test',
2488 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2490 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2491 is( $credit_return_id, undef, 'No LOST_FOUND account line added' );
2493 $lost_fee_line->discard_changes; # reload from DB
2494 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2495 is( $lost_fee_line->debit_type_code,
2496 'LOST', 'Lost fee now still has account type of LOST' );
2497 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2499 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2502 subtest 'Full payment tests' => sub {
2504 plan tests => 13;
2506 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2508 my $item = $builder->build_sample_item(
2510 biblionumber => $biblio->biblionumber,
2511 library => $library->branchcode,
2512 replacementprice => $replacement_amount,
2513 itype => $item_type->itemtype
2517 AddIssue( $patron->unblessed, $item->barcode );
2519 # Simulate item marked as lost
2520 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2521 LostItem( $item->itemnumber, 1 );
2523 my $processing_fee_lines = Koha::Account::Lines->search(
2524 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2525 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2526 my $processing_fee_line = $processing_fee_lines->next;
2527 is( $processing_fee_line->amount + 0,
2528 $processfee_amount, 'The right PROCESSING amount is generated' );
2529 is( $processing_fee_line->amountoutstanding + 0,
2530 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2532 my $lost_fee_lines = Koha::Account::Lines->search(
2533 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2534 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2535 my $lost_fee_line = $lost_fee_lines->next;
2536 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2537 is( $lost_fee_line->amountoutstanding + 0,
2538 $replacement_amount, 'The right LOST amountountstanding is generated' );
2540 my $account = $patron->account;
2541 my $debts = $account->outstanding_debits;
2543 # Write off the debt
2544 my $credit = $account->add_credit(
2545 { amount => $account->balance,
2546 type => 'PAYMENT',
2547 interface => 'test',
2550 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2552 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2553 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2555 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2556 is( $credit_return->amount + 0,
2557 -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2558 is( $credit_return->amountoutstanding + 0,
2559 -99.00, 'The account line of type LOST_FOUND has an amountoutstanding of -99' );
2561 $lost_fee_line->discard_changes;
2562 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2563 is( $lost_fee_line->debit_type_code,
2564 'LOST', 'Lost fee now still has account type of LOST' );
2565 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2567 is( $patron->account->balance,
2568 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2571 subtest 'Test without payment or write off' => sub {
2573 plan tests => 13;
2575 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2577 my $item = $builder->build_sample_item(
2579 biblionumber => $biblio->biblionumber,
2580 library => $library->branchcode,
2581 replacementprice => 23.00,
2582 replacementprice => $replacement_amount,
2583 itype => $item_type->itemtype
2587 AddIssue( $patron->unblessed, $item->barcode );
2589 # Simulate item marked as lost
2590 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2591 LostItem( $item->itemnumber, 1 );
2593 my $processing_fee_lines = Koha::Account::Lines->search(
2594 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2595 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2596 my $processing_fee_line = $processing_fee_lines->next;
2597 is( $processing_fee_line->amount + 0,
2598 $processfee_amount, 'The right PROCESSING amount is generated' );
2599 is( $processing_fee_line->amountoutstanding + 0,
2600 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2602 my $lost_fee_lines = Koha::Account::Lines->search(
2603 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2604 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2605 my $lost_fee_line = $lost_fee_lines->next;
2606 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2607 is( $lost_fee_line->amountoutstanding + 0,
2608 $replacement_amount, 'The right LOST amountountstanding is generated' );
2610 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2611 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2613 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2614 is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2615 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_FOUND has an amountoutstanding of 0' );
2617 $lost_fee_line->discard_changes;
2618 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2619 is( $lost_fee_line->debit_type_code,
2620 'LOST', 'Lost fee now still has account type of LOST' );
2621 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2623 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2626 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2628 plan tests => 16;
2630 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2631 my $item = $builder->build_sample_item(
2633 biblionumber => $biblio->biblionumber,
2634 library => $library->branchcode,
2635 replacementprice => $replacement_amount,
2636 itype => $item_type->itemtype
2640 AddIssue( $patron->unblessed, $item->barcode );
2642 # Simulate item marked as lost
2643 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2644 LostItem( $item->itemnumber, 1 );
2646 my $processing_fee_lines = Koha::Account::Lines->search(
2647 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2648 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2649 my $processing_fee_line = $processing_fee_lines->next;
2650 is( $processing_fee_line->amount + 0,
2651 $processfee_amount, 'The right PROCESSING amount is generated' );
2652 is( $processing_fee_line->amountoutstanding + 0,
2653 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2655 my $lost_fee_lines = Koha::Account::Lines->search(
2656 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2657 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2658 my $lost_fee_line = $lost_fee_lines->next;
2659 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2660 is( $lost_fee_line->amountoutstanding + 0,
2661 $replacement_amount, 'The right LOST amountountstanding is generated' );
2663 my $account = $patron->account;
2664 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2666 # Partially pay fee
2667 my $payment_amount = 27;
2668 my $payment = $account->add_credit(
2669 { amount => $payment_amount,
2670 type => 'PAYMENT',
2671 interface => 'test',
2675 $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2677 # Partially write off fee
2678 my $write_off_amount = 25;
2679 my $write_off = $account->add_credit(
2680 { amount => $write_off_amount,
2681 type => 'WRITEOFF',
2682 interface => 'test',
2685 $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2687 is( $account->balance,
2688 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2689 'Payment and write off applied'
2692 # Store the amountoutstanding value
2693 $lost_fee_line->discard_changes;
2694 my $outstanding = $lost_fee_line->amountoutstanding;
2696 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2697 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2699 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_FOUND)' );
2701 $lost_fee_line->discard_changes;
2702 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2703 is( $lost_fee_line->debit_type_code,
2704 'LOST', 'Lost fee now still has account type of LOST' );
2705 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2707 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2708 is( $credit_return->amount + 0,
2709 ($payment_amount + $outstanding ) * -1,
2710 'The account line of type LOST_FOUND has an amount equal to the payment + outstanding'
2712 is( $credit_return->amountoutstanding + 0,
2713 $payment_amount * -1,
2714 'The account line of type LOST_FOUND has an amountoutstanding equal to the payment'
2717 is( $account->balance,
2718 $processfee_amount - $payment_amount,
2719 'The patron balance is the difference between the PROCESSING and the credit'
2723 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2725 plan tests => 8;
2727 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2728 my $barcode = 'KD123456793';
2729 my $replacement_amount = 100;
2730 my $processfee_amount = 20;
2732 my $item_type = $builder->build_object(
2733 { class => 'Koha::ItemTypes',
2734 value => {
2735 notforloan => undef,
2736 rentalcharge => 0,
2737 defaultreplacecost => undef,
2738 processfee => 0,
2739 rentalcharge_daily => 0,
2743 my ( undef, undef, $item_id ) = AddItem(
2744 { homebranch => $library->branchcode,
2745 holdingbranch => $library->branchcode,
2746 barcode => $barcode,
2747 replacementprice => $replacement_amount,
2748 itype => $item_type->itemtype
2750 $biblio->biblionumber
2753 AddIssue( $patron->unblessed, $barcode );
2755 # Simulate item marked as lost
2756 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2757 LostItem( $item_id, 1 );
2759 my $lost_fee_lines = Koha::Account::Lines->search(
2760 { borrowernumber => $patron->id, itemnumber => $item_id, debit_type_code => 'LOST' } );
2761 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2762 my $lost_fee_line = $lost_fee_lines->next;
2763 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2764 is( $lost_fee_line->amountoutstanding + 0,
2765 $replacement_amount, 'The right LOST amountountstanding is generated' );
2767 my $account = $patron->account;
2768 is( $account->balance, $replacement_amount, 'Balance is L' );
2770 # Partially pay fee
2771 my $payment_amount = 27;
2772 my $payment = $account->add_credit(
2773 { amount => $payment_amount,
2774 type => 'PAYMENT',
2775 interface => 'test',
2778 $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2780 is( $account->balance,
2781 $replacement_amount - $payment_amount,
2782 'Payment applied'
2785 my $manual_debit_amount = 80;
2786 $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2788 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2790 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2792 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item_id, $patron->id );
2793 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2795 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_FOUND)' );
2797 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2798 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2802 subtest '_FixOverduesOnReturn' => sub {
2803 plan tests => 11;
2805 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2806 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2808 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2810 my $branchcode = $library2->{branchcode};
2812 my $item = $builder->build_sample_item(
2814 biblionumber => $biblio->biblionumber,
2815 library => $branchcode,
2816 replacementprice => 99.00,
2817 itype => $itemtype,
2821 my $patron = $builder->build( { source => 'Borrower' } );
2823 ## Start with basic call, should just close out the open fine
2824 my $accountline = Koha::Account::Line->new(
2826 borrowernumber => $patron->{borrowernumber},
2827 debit_type_code => 'OVERDUE',
2828 status => 'UNRETURNED',
2829 itemnumber => $item->itemnumber,
2830 amount => 99.00,
2831 amountoutstanding => 99.00,
2832 interface => 'test',
2834 )->store();
2836 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2838 $accountline->_result()->discard_changes();
2840 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
2841 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2842 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2844 ## Run again, with exemptfine enabled
2845 $accountline->set(
2847 debit_type_code => 'OVERDUE',
2848 status => 'UNRETURNED',
2849 amountoutstanding => 99.00,
2851 )->store();
2853 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2855 $accountline->_result()->discard_changes();
2856 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2858 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2859 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2860 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2861 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2862 is( $offset->amount + 0, -99, "Amount of offset is correct" );
2863 my $credit = $offset->credit;
2864 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2865 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2866 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2869 subtest '_FixAccountForLostAndFound returns undef if patron is deleted' => sub {
2870 plan tests => 1;
2872 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2873 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2875 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2877 my $branchcode = $library2->{branchcode};
2879 my $item = $builder->build_sample_item(
2881 biblionumber => $biblio->biblionumber,
2882 library => $branchcode,
2883 replacementprice => 99.00,
2884 itype => $itemtype,
2888 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2890 ## Start with basic call, should just close out the open fine
2891 my $accountline = Koha::Account::Line->new(
2893 borrowernumber => $patron->id,
2894 debit_type_code => 'LOST',
2895 status => undef,
2896 itemnumber => $item->itemnumber,
2897 amount => 99.00,
2898 amountoutstanding => 99.00,
2899 interface => 'test',
2901 )->store();
2903 $patron->delete();
2905 my $return_value = C4::Circulation::_FixAccountForLostAndFound( $patron->id, $item->itemnumber );
2907 is( $return_value, undef, "_FixAccountForLostAndFound returns undef if patron is deleted" );
2911 subtest 'Set waiting flag' => sub {
2912 plan tests => 11;
2914 my $library_1 = $builder->build( { source => 'Branch' } );
2915 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2916 my $library_2 = $builder->build( { source => 'Branch' } );
2917 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2919 my $item = $builder->build_sample_item(
2921 library => $library_1->{branchcode},
2923 )->unblessed;
2925 set_userenv( $library_2 );
2926 my $reserve_id = AddReserve(
2928 branchcode => $library_2->{branchcode},
2929 borrowernumber => $patron_2->{borrowernumber},
2930 biblionumber => $item->{biblionumber},
2931 priority => 1,
2932 itemnumber => $item->{itemnumber},
2936 set_userenv( $library_1 );
2937 my $do_transfer = 1;
2938 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2939 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2940 my $hold = Koha::Holds->find( $reserve_id );
2941 is( $hold->found, 'T', 'Hold is in transit' );
2943 my ( $status ) = CheckReserves($item->{itemnumber});
2944 is( $status, 'Reserved', 'Hold is not waiting yet');
2946 set_userenv( $library_2 );
2947 $do_transfer = 0;
2948 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2949 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2950 $hold = Koha::Holds->find( $reserve_id );
2951 is( $hold->found, 'W', 'Hold is waiting' );
2952 ( $status ) = CheckReserves($item->{itemnumber});
2953 is( $status, 'Waiting', 'Now the hold is waiting');
2955 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
2956 set_userenv( $library_1 );
2957 (undef, my $messages, undef, undef ) = AddReturn ( $item->{barcode}, $library_1->{branchcode} );
2958 $hold = Koha::Holds->find( $reserve_id );
2959 is( $hold->found, undef, 'Hold is no longer marked waiting' );
2960 is( $hold->priority, 1, "Hold is now priority one again");
2961 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
2962 is( $hold->itemnumber, $item->{itemnumber}, "Hold has retained its' itemnumber");
2963 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
2964 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
2965 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
2968 subtest 'Cancel transfers on lost items' => sub {
2969 plan tests => 5;
2970 my $library_1 = $builder->build( { source => 'Branch' } );
2971 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2972 my $library_2 = $builder->build( { source => 'Branch' } );
2973 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2974 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2975 my $item = $builder->build_sample_item({
2976 biblionumber => $biblio->biblionumber,
2977 library => $library_1->{branchcode},
2980 set_userenv( $library_2 );
2981 my $reserve_id = AddReserve(
2983 branchcode => $library_2->{branchcode},
2984 borrowernumber => $patron_2->{borrowernumber},
2985 biblionumber => $item->biblionumber,
2986 priority => 1,
2987 itemnumber => $item->itemnumber,
2991 #Return book and add transfer
2992 set_userenv( $library_1 );
2993 my $do_transfer = 1;
2994 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
2995 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
2996 C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
2997 my $hold = Koha::Holds->find( $reserve_id );
2998 is( $hold->found, 'T', 'Hold is in transit' );
3000 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3001 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3002 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
3003 my $itemcheck = Koha::Items->find($item->itemnumber);
3004 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
3006 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3007 ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
3008 LostItem( $item->itemnumber, 'test', 1 );
3009 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3010 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3011 $itemcheck = Koha::Items->find($item->itemnumber);
3012 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3015 subtest 'CanBookBeIssued | is_overdue' => sub {
3016 plan tests => 3;
3018 # Set a simple circ policy
3019 Koha::CirculationRules->set_rules(
3021 categorycode => undef,
3022 branchcode => undef,
3023 itemtype => undef,
3024 rules => {
3025 maxissueqty => 1,
3026 reservesallowed => 25,
3027 issuelength => 14,
3028 lengthunit => 'days',
3029 renewalsallowed => 1,
3030 renewalperiod => 7,
3031 norenewalbefore => undef,
3032 auto_renew => 0,
3033 fine => .10,
3034 chargeperiod => 1,
3039 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
3040 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
3041 my $library = $builder->build( { source => 'Branch' } );
3042 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3044 my $item = $builder->build_sample_item(
3046 library => $library->{branchcode},
3048 )->unblessed;
3050 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
3051 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
3052 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3053 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
3054 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3055 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3058 subtest 'ItemsDeniedRenewal preference' => sub {
3059 plan tests => 18;
3061 C4::Context->set_preference('ItemsDeniedRenewal','');
3063 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3064 Koha::CirculationRules->set_rules(
3066 categorycode => '*',
3067 itemtype => '*',
3068 branchcode => $idr_lib->branchcode,
3069 rules => {
3070 reservesallowed => 25,
3071 issuelength => 14,
3072 lengthunit => 'days',
3073 renewalsallowed => 10,
3074 renewalperiod => 7,
3075 norenewalbefore => undef,
3076 auto_renew => 0,
3077 fine => .10,
3078 chargeperiod => 1,
3083 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3084 homebranch => $idr_lib->branchcode,
3085 withdrawn => 1,
3086 itype => 'HIDE',
3087 location => 'PROC',
3088 itemcallnumber => undef,
3089 itemnotes => "",
3092 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3093 homebranch => $idr_lib->branchcode,
3094 withdrawn => 0,
3095 itype => 'NOHIDE',
3096 location => 'NOPROC'
3100 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3101 branchcode => $idr_lib->branchcode,
3104 my $future = dt_from_string->add( days => 1 );
3105 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3106 returndate => undef,
3107 renewals => 0,
3108 auto_renew => 0,
3109 borrowernumber => $idr_borrower->borrowernumber,
3110 itemnumber => $deny_book->itemnumber,
3111 onsite_checkout => 0,
3112 date_due => $future,
3115 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3116 returndate => undef,
3117 renewals => 0,
3118 auto_renew => 0,
3119 borrowernumber => $idr_borrower->borrowernumber,
3120 itemnumber => $allow_book->itemnumber,
3121 onsite_checkout => 0,
3122 date_due => $future,
3126 my $idr_rules;
3128 my ( $idr_mayrenew, $idr_error ) =
3129 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3130 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3131 is( $idr_error, undef, 'Renewal allowed when no rules' );
3133 $idr_rules="withdrawn: [1]";
3135 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3136 ( $idr_mayrenew, $idr_error ) =
3137 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3138 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3139 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3140 ( $idr_mayrenew, $idr_error ) =
3141 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3142 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3143 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3145 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3147 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3148 ( $idr_mayrenew, $idr_error ) =
3149 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3150 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3151 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3152 ( $idr_mayrenew, $idr_error ) =
3153 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3154 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3155 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3157 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3159 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3160 ( $idr_mayrenew, $idr_error ) =
3161 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3162 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3163 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3164 ( $idr_mayrenew, $idr_error ) =
3165 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3166 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3167 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3169 $idr_rules="itemcallnumber: [NULL]";
3170 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3171 ( $idr_mayrenew, $idr_error ) =
3172 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3173 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3174 $idr_rules="itemcallnumber: ['']";
3175 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3176 ( $idr_mayrenew, $idr_error ) =
3177 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3178 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3180 $idr_rules="itemnotes: [NULL]";
3181 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3182 ( $idr_mayrenew, $idr_error ) =
3183 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3184 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3185 $idr_rules="itemnotes: ['']";
3186 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3187 ( $idr_mayrenew, $idr_error ) =
3188 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3189 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3192 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3193 plan tests => 2;
3195 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3196 my $library = $builder->build( { source => 'Branch' } );
3197 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3199 my $item = $builder->build_sample_item(
3201 library => $library->{branchcode},
3205 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3206 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3207 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3210 subtest 'CanBookBeIssued | notforloan' => sub {
3211 plan tests => 2;
3213 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3215 my $library = $builder->build( { source => 'Branch' } );
3216 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3218 my $itemtype = $builder->build(
3220 source => 'Itemtype',
3221 value => { notforloan => undef, }
3224 my $item = $builder->build_sample_item(
3226 library => $library->{branchcode},
3227 itype => $itemtype->{itemtype},
3230 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3232 my ( $issuingimpossible, $needsconfirmation );
3235 subtest 'item-level_itypes = 1' => sub {
3236 plan tests => 6;
3238 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3239 # Is for loan at item type and item level
3240 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3241 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3242 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3244 # not for loan at item type level
3245 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3246 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3247 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3248 is_deeply(
3249 $issuingimpossible,
3250 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3251 'Item can not be issued, not for loan at item type level'
3254 # not for loan at item level
3255 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3256 $item->notforloan( 1 )->store;
3257 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3258 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3259 is_deeply(
3260 $issuingimpossible,
3261 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3262 'Item can not be issued, not for loan at item type level'
3266 subtest 'item-level_itypes = 0' => sub {
3267 plan tests => 6;
3269 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3271 # We set another itemtype for biblioitem
3272 my $itemtype = $builder->build(
3274 source => 'Itemtype',
3275 value => { notforloan => undef, }
3279 # for loan at item type and item level
3280 $item->notforloan(0)->store;
3281 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3282 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3283 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3284 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3286 # not for loan at item type level
3287 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3288 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3289 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3290 is_deeply(
3291 $issuingimpossible,
3292 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3293 'Item can not be issued, not for loan at item type level'
3296 # not for loan at item level
3297 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3298 $item->notforloan( 1 )->store;
3299 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3300 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3301 is_deeply(
3302 $issuingimpossible,
3303 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3304 'Item can not be issued, not for loan at item type level'
3308 # TODO test with AllowNotForLoanOverride = 1
3311 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3312 plan tests => 1;
3314 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3315 my $item = $builder->build_sample_item(
3317 onloan => '2018-01-01',
3321 AddReturn( $item->barcode, $item->homebranch );
3322 $item->discard_changes; # refresh
3323 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3327 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3329 plan tests => 11;
3332 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3334 my $issuing_charges = 15;
3335 my $title = 'A title';
3336 my $author = 'Author, An';
3337 my $barcode = 'WHATARETHEODDS';
3339 my $circ = Test::MockModule->new('C4::Circulation');
3340 $circ->mock(
3341 'GetIssuingCharges',
3342 sub {
3343 return $issuing_charges;
3347 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3348 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3349 my $patron = $builder->build_object({
3350 class => 'Koha::Patrons',
3351 value => { branchcode => $library->id }
3354 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3355 my ( undef, undef, $item_id ) = AddItem(
3357 homebranch => $library->id,
3358 holdingbranch => $library->id,
3359 barcode => $barcode,
3360 replacementprice => 23.00,
3361 itype => $itemtype->id
3363 $biblio->biblionumber
3365 my $item = Koha::Items->find( $item_id );
3367 my $context = Test::MockModule->new('C4::Context');
3368 $context->mock( userenv => { branch => $library->id } );
3370 # Check the item out
3371 AddIssue( $patron->unblessed, $item->barcode );
3372 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3373 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3374 my %params_renewal = (
3375 timestamp => { -like => $date . "%" },
3376 module => "CIRCULATION",
3377 action => "RENEWAL",
3379 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3380 AddRenewal( $patron->id, $item->id, $library->id );
3381 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3382 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3384 my $checkouts = $patron->checkouts;
3385 # The following will fail if run on 00:00:00
3386 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3388 my $lines = Koha::Account::Lines->search({
3389 borrowernumber => $patron->id,
3390 itemnumber => $item->id
3393 is( $lines->count, 2 );
3395 my $line = $lines->next;
3396 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3397 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3398 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3400 $line = $lines->next;
3401 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3402 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3403 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3405 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3407 $context = Test::MockModule->new('C4::Context');
3408 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3410 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3411 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3412 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3413 $sth->execute($item->id, $library->id);
3414 my ($old_stats_size) = $sth->fetchrow_array;
3415 AddRenewal( $patron->id, $item->id, $library->id );
3416 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3417 $sth->execute($item->id, $library->id);
3418 my ($new_stats_size) = $sth->fetchrow_array;
3419 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3420 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3424 subtest 'ProcessOfflinePayment() tests' => sub {
3426 plan tests => 4;
3429 my $amount = 123;
3431 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3432 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3433 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3435 is( $result, 'Success.', 'The right string is returned' );
3437 my $lines = $patron->account->lines;
3438 is( $lines->count, 1, 'line created correctly');
3440 my $line = $lines->next;
3441 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3442 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3446 subtest 'Incremented fee tests' => sub {
3447 plan tests => 19;
3449 my $dt = dt_from_string();
3450 Time::Fake->offset( $dt->epoch );
3452 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3454 my $library =
3455 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3457 my $module = new Test::MockModule('C4::Context');
3458 $module->mock( 'userenv', sub { { branch => $library->id } } );
3460 my $patron = $builder->build_object(
3462 class => 'Koha::Patrons',
3463 value => { categorycode => $patron_category->{categorycode} }
3465 )->store;
3467 my $itemtype = $builder->build_object(
3469 class => 'Koha::ItemTypes',
3470 value => {
3471 notforloan => undef,
3472 rentalcharge => 0,
3473 rentalcharge_daily => 1,
3476 )->store;
3478 my $item = $builder->build_sample_item(
3480 library => $library->{branchcode},
3481 itype => $itemtype->id,
3485 is( $itemtype->rentalcharge_daily+0,
3486 1, 'Daily rental charge stored and retreived correctly' );
3487 is( $item->effective_itemtype, $itemtype->id,
3488 "Itemtype set correctly for item" );
3490 my $dt_from = dt_from_string();
3491 my $dt_to = dt_from_string()->add( days => 7 );
3492 my $dt_to_renew = dt_from_string()->add( days => 13 );
3494 # Daily Tests
3495 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3496 my $issue =
3497 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3498 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3499 is( $accountline->amount+0, 7,
3500 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3502 $accountline->delete();
3503 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3504 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3505 is( $accountline->amount+0, 6,
3506 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3508 $accountline->delete();
3509 $issue->delete();
3511 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3512 $issue =
3513 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3514 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3515 is( $accountline->amount+0, 7,
3516 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3518 $accountline->delete();
3519 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3520 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3521 is( $accountline->amount+0, 6,
3522 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3524 $accountline->delete();
3525 $issue->delete();
3527 my $calendar = C4::Calendar->new( branchcode => $library->id );
3528 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3529 my $closed_day =
3530 ( $dt_from->day_of_week == 6 ) ? 0
3531 : ( $dt_from->day_of_week == 7 ) ? 1
3532 : $dt_from->day_of_week + 1;
3533 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3534 $calendar->insert_week_day_holiday(
3535 weekday => $closed_day,
3536 title => 'Test holiday',
3537 description => 'Test holiday'
3539 $issue =
3540 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3541 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3542 is( $accountline->amount+0, 6,
3543 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name"
3545 $accountline->delete();
3546 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3547 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3548 is( $accountline->amount+0, 5,
3549 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal"
3551 $accountline->delete();
3552 $issue->delete();
3554 $itemtype->rentalcharge(2)->store;
3555 is( $itemtype->rentalcharge+0, 2,
3556 'Rental charge updated and retreived correctly' );
3557 $issue =
3558 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3559 my $accountlines =
3560 Koha::Account::Lines->search( { itemnumber => $item->id } );
3561 is( $accountlines->count, '2',
3562 "Fixed charge and accrued charge recorded distinctly" );
3563 $accountlines->delete();
3564 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3565 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3566 is( $accountlines->count, '2',
3567 "Fixed charge and accrued charge recorded distinctly, for renewal" );
3568 $accountlines->delete();
3569 $issue->delete();
3570 $itemtype->rentalcharge(0)->store;
3571 is( $itemtype->rentalcharge+0, 0,
3572 'Rental charge reset and retreived correctly' );
3574 # Hourly
3575 Koha::CirculationRules->set_rule(
3577 categorycode => $patron->categorycode,
3578 itemtype => $itemtype->id,
3579 branchcode => $library->id,
3580 rule_name => 'lengthunit',
3581 rule_value => 'hours',
3585 $itemtype->rentalcharge_hourly('0.25')->store();
3586 is( $itemtype->rentalcharge_hourly,
3587 '0.25', 'Hourly rental charge stored and retreived correctly' );
3589 $dt_to = dt_from_string()->add( hours => 168 );
3590 $dt_to_renew = dt_from_string()->add( hours => 312 );
3592 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3593 $issue =
3594 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3595 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3596 is( $accountline->amount + 0, 42,
3597 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3598 $accountline->delete();
3599 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3600 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3601 is( $accountline->amount + 0, 36,
3602 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3603 $accountline->delete();
3604 $issue->delete();
3606 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3607 $issue =
3608 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3609 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3610 is( $accountline->amount + 0, 36,
3611 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name (168h - 24h * 0.25u)" );
3612 $accountline->delete();
3613 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3614 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3615 is( $accountline->amount + 0, 30,
3616 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3617 $accountline->delete();
3618 $issue->delete();
3620 $calendar->delete_holiday( weekday => $closed_day );
3621 $issue =
3622 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3623 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3624 is( $accountline->amount + 0, 42,
3625 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3626 $accountline->delete();
3627 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3628 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3629 is( $accountline->amount + 0, 36,
3630 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3631 $accountline->delete();
3632 $issue->delete();
3633 Time::Fake->reset;
3636 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3637 plan tests => 2;
3639 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3640 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3642 my $library =
3643 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3644 my $patron = $builder->build_object(
3646 class => 'Koha::Patrons',
3647 value => { categorycode => $patron_category->{categorycode} }
3649 )->store;
3651 my $itemtype = $builder->build_object(
3653 class => 'Koha::ItemTypes',
3654 value => {
3655 notforloan => 0,
3656 rentalcharge => 0,
3657 rentalcharge_daily => 0
3662 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3663 my $item = $builder->build_object(
3665 class => 'Koha::Items',
3666 value => {
3667 homebranch => $library->id,
3668 holdingbranch => $library->id,
3669 notforloan => 0,
3670 itemlost => 0,
3671 withdrawn => 0,
3672 itype => $itemtype->id,
3673 biblionumber => $biblioitem->{biblionumber},
3674 biblioitemnumber => $biblioitem->{biblioitemnumber},
3677 )->store;
3679 my ( $issuingimpossible, $needsconfirmation );
3680 my $dt_from = dt_from_string();
3681 my $dt_due = dt_from_string()->add( days => 3 );
3683 $itemtype->rentalcharge(1)->store;
3684 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3685 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3686 $itemtype->rentalcharge('0')->store;
3687 $itemtype->rentalcharge_daily(1)->store;
3688 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3689 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3690 $itemtype->rentalcharge_daily('0')->store;
3693 subtest "Test Backdating of Returns" => sub {
3694 plan tests => 2;
3696 my $branch = $library2->{branchcode};
3697 my $biblio = $builder->build_sample_biblio();
3698 my $item = $builder->build_sample_item(
3700 biblionumber => $biblio->biblionumber,
3701 library => $branch,
3702 itype => $itemtype,
3706 my %a_borrower_data = (
3707 firstname => 'Kyle',
3708 surname => 'Hall',
3709 categorycode => $patron_category->{categorycode},
3710 branchcode => $branch,
3712 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3713 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3715 my $due_date = dt_from_string;
3716 my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3717 UpdateFine(
3719 issue_id => $issue->id(),
3720 itemnumber => $item->itemnumber,
3721 borrowernumber => $borrowernumber,
3722 amount => .25,
3723 amountoutstanding => .25,
3724 type => q{}
3729 my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3731 my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3732 is( $accountline->amountoutstanding+0, 0, 'Fee amount outstanding was reduced to 0' );
3733 is( $accountline->amount+0, 0, 'Fee amount was reduced to 0' );
3736 $schema->storage->txn_rollback;
3737 C4::Context->clear_syspref_cache();
3738 $cache->clear_from_cache('single_holidays');